package com.ruoyi.excelFileIoHandler;

import com.ruoyi.common.annotation.Excel;
import com.ruoyi.mqttClient.AutoSendMsgMqttCallback;
import org.junit.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Component;


import java.lang.reflect.Field;


/**
 * @author jitwxs
 * @date 2023年12月10日 17:31
 */

@Component("testExcel")
public class TestExcel {
    private final static String filePath = "C:\\Users\\Administrator\\Desktop";
    private final static String fileName = "testExcel.xls";
    @Autowired
    public ReadExcel readExcel;
    @Autowired
    public AutoSendMsgMqttCallback autoSendMsgMqttCallback;

    public void readFileAndSendMqtt() {
        autoSendMsgMqttCallback.init();
        readExcel.readExcelTest(filePath, fileName, 0, 0, 0);

    }

    /**
     * 用反射方法，获取列名，比较，为属性赋值
     *
     * @param object
     * @param fieldName
     * @param val
     */
    public static void setFieldValueByFieldName(Object object, String fieldName, Object val) {
        try {
            //通过反射获取所有实体类所有定义的方法,object为数据库实体类
            Field[] fields = object.getClass().getDeclaredFields();
            //遍历fields
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                //读取注释，如@Excel(name = "科目")
                Excel annotation = field.getAnnotation(Excel.class);
                //因为private类型，所有要设置允许
                field.setAccessible(true);
                //annotation.name() 注解里的属性,如果annotation没写注解，读取原始名字如subject
                if (annotation == null) {
                    if (fieldName.equals(field.getName())) {
                        if (field.getType() == Integer.class) {
                            field.set(object, Integer.valueOf(val.toString()));
                        } else if (field.getType() == Long.class) {
                            field.set(object, Long.valueOf(val.toString()));
                        } else {
                            field.set(object, val);
                        }
                        return;
                    }
                } else {//设置了注解，并且表格里的Excel字段值和注解的name值相同，则为相应字段赋值
                    if (fieldName.equals(annotation.name())) {
                        //进行类型判断，因为实体类中变量类型不同。
                        if (field.getType() == Integer.class) {
                            field.set(object, Integer.valueOf(val.toString()));
                        } else if (field.getType() == Long.class) {
                            field.set(object, Long.valueOf(val.toString()));
                        } else {
                            field.set(object, val);
                        }
                        return;
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
